package kuzmenkov.oip.adapters.sun.jai;

import kuzmenkov.oip.adapters.ImageProcessingAdapter;
import kuzmenkov.oip.common.FileTool;

import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import java.awt.geom.Rectangle2D;
import java.awt.image.renderable.ParameterBlock;
import java.net.URL;
import java.util.logging.Logger;

/**
 * The class adapts JAT Median Filtering
 * User: Michael Kuzmenkov
 * Date: 26.03.2009
 * Time: 1:32:53
 */
public class CroppingAdapter extends ImageProcessingAdapter {
    private static final Logger log = Logger.getLogger(MedianFilteringAdapter.class.getName());


    /**
     * It takes two parameters. First parameter is the path to the image (String).
     * Second parameter is the area selection (java.awt.geom.Rectangle2D).
     *
     * @param params the input parameters
     * @return the path to the output image
     */
    public Object[] process(Object[] params) throws Exception {
        
        String path = (String) params[0];
        Rectangle2D selection = (Rectangle2D) params[1];
        log.info("path=" + path + ", selection=" + selection);

        FileTool ftool = FileTool.getInstance();
        path = ftool.relPathToAbs(path);
        RenderedOp srcImage = JAI.create("fileload", path);        
        log.info("srcImage=" + srcImage);

        Float x = (float) selection.getX();
        Float y = (float) selection.getY();
        Float width = (float) selection.getWidth();
        Float height = (float) selection.getHeight();


        ParameterBlock block = new ParameterBlock();
        block.addSource(srcImage);
        block.add(x);
        block.add(y);
        block.add(width);
        block.add(height);
        RenderedOp cropImage = JAI.create("crop", block, null);

        // Translate the image origin.
        block = new ParameterBlock();
        block.addSource(cropImage);
        block.add(-x);
        block.add(-y);
        // Create the output image by translating itself.
        RenderedOp dstImage = JAI.create("translate", block, null);

        String dstFileName = "1.png";
        String dstPath = ftool.getTempDir(getSessionId())+dstFileName;
        log.info("destination path="+dstPath);
        JAI.create("filestore", dstImage, dstPath, "PNG", null);

        String relDstPath = ftool.getRelativeTempDir(getSessionId())+dstFileName;
        log.info("relative destination path="+relDstPath);
        return new Object[]{relDstPath};        
    }
}